#include <vector>
#include <iostream>
#include <numeric>
#include <algorithm>
using namespace std;

int cal(vector<int> &num, vector<int> &result, vector<int> &rec, int n)
{
        if(n == 0){
                rec[0] = 0;
                return result[0] = 1;
        }

        cal(num, result, rec, n -1);
        for(int i = 0; i < n; i++){
                if(num[i] <= num[n]){
                        if(result[n] < result[i] + 1){
                                rec[n] = i;
                                result[n] = result[i] + 1;
                        }
                }
        }
        return result[n];
}

void dp(vector<int> &num, vector<int> &result, vector<int> &rec)
{
        for(int i = 1; i < result.size(); i++){
                for(int j = 0; j < i; j++){
                        if(num[j] <= num[i]){
                                if(result[i] < result[j] + 1){
                                        rec[i] = j;
                                        result[i] = result[j] + 1;
                                }
                        }
                }
        }
}

int dfs(vector<int> &num, vector<int> &rec, int n)
{
        if(rec[n] != n){
                dfs(num, rec, rec[n]);
        }
        cout<<num[n]<<' ';
        return 0;
}

int main()
{
        int n;
        cin>>n;
        vector<int> num(n, 0), result(n, 1), rec(n, -1);
        iota(rec.begin(), rec.end(), 0);

        for(int i = 0; i < n; i++)
                cin>>num[i];

        //cal(num, result, rec, n - 1);
        dp(num, result, rec);

        int maxlen = 0, maxidx = -1;
        for(int i = 0; i < n; i++){
                if(result[i] > maxlen){
                        maxlen = result[i];
                        maxidx = i;
                }
        }
        cout<<"max="<<maxlen<<endl;
        dfs(num, rec, maxidx);
        cout<<endl;        
        return 0;
}